# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from com.arcfox.util import constant

# 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在CosConfig中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = constant.COS_SECRET_ID  # 替换为用户的 SecretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
secret_key = constant.COS_SECRET_KEY  # 替换为用户的 SecretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
region = constant.COS_REGION  # 替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket


def get_client():
    config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)  # 获取配置对象
    return CosS3Client(config)


def upload_by_file(file_name, bucket=constant.COS_BUCKET_SCHOOL):
    with open(file_name, 'rb') as fp:
        response = get_client().put_object(
            Bucket=bucket,
            Body=fp,
            Key=file_name,
            StorageClass='STANDARD',
            ContentType='text/html; charset=utf-8',
        )
        return response['ETag']


def upload_by_bytes(file_name, byte_body, bucket=constant.COS_BUCKET_SCHOOL):
    # 字节流 简单上传
    response = get_client().put_object(
        Bucket=bucket,
        Body=byte_body,
        Key=file_name
    )
    return response['ETag']


def get_signed_url(img_name, bucket=constant.COS_BUCKET_SCHOOL):
    # 生成URL
    return get_client().get_presigned_url(
        Bucket=bucket,
        Key=img_name,
        Expired=120,
        Method='Get'
    )


if __name__ == "__main__":
    print(get_signed_url("2564f6fc63448363103b22752ff72456/fdf7a157ed9114d3fb98aef776eba52c.jpg",
                         constant.COS_BUCKET_SCHOOL_IMG))
